<template>
  <BaseDialog
    :title="title"
    :handleCancel="handleCancel"
    :handleOk="handleOk"
    width="1100px"
    v-model:dialogVisible="props.dialogVisible"
    :footer="true"
  >
    <div class="dialog__body">
      <div class="left">
        <div class="use_titile">选择{{ props.selectTitle }}</div>
        <BaseForm
          ref="searchForm"
          type="search"
          :items="props.formItems"
          v-model:form="queryData"
          style="padding: 16px 16px 0 16px"
          @search="handleSearch"
        >
        </BaseForm>
        <template
          v-if="props.type === 'checkBox' || props.type === 'cate-list'"
        >
          <el-checkbox
            v-if="!props.custom_checkBox"
            :indeterminate="indeterminate"
            @change="selectAll"
            v-model="checkAll"
            >全选</el-checkbox
          >
          <el-scrollbar
            v-loading="loading"
            element-loading-text="加载中..."
            class="scrollBox"
            style="height: 320px; padding-left: 10px; padding-top: 10px"
          >
            <slot
              v-if="props.custom_checkBox"
              name="custom_checkBox"
              :list="list"
            ></slot>

            <el-collapse
              v-else-if="props.type === 'cate-list'"
              v-model="activeNames"
            >
              <div v-for="(item, j) in list" :key="j" style="display: flex">
                <el-checkbox v-model="item.checked" @change="onChange(item)">
                </el-checkbox>
                <el-collapse-item :name="j">
                  <template #title>
                    <span style="color: #999">
                      <slot name="cateName" :item="item"></slot>
                    </span>
                  </template>
                  <div
                    v-for="(n, i) in item[props.cateListChildrenKey]"
                    :key="i"
                  >
                    <span style="padding-left: 30px">
                      <el-checkbox v-model="n.checked" @change="onChange(n)">
                        <slot name="checkboxName" :item="n"></slot>
                      </el-checkbox>
                    </span>
                  </div>
                </el-collapse-item>
              </div>
            </el-collapse>
            <div
              v-else-if="props.type === 'checkBox'"
              v-for="(n, i) in list"
              :key="i"
              style=""
            >
              <el-checkbox v-model="n.checked" @change="onChange(n)">
                <slot name="checkboxName" :item="n"></slot>
              </el-checkbox>
            </div>
            <div v-if="list.length === 0" class="no_data">暂无数据</div>
          </el-scrollbar>
        </template>

        <el-table
          v-else-if="props.type === 'table'"
          border
          ref="multipleTableRef"
          v-loading="loading"
          element-loading-text="加载中..."
          :data="list"
          max-height="320px"
          @select="handleSelectionChange"
          @select-all="selectAll"
          :row-key="getRowKeys"
        >
          <el-table-column
            :reserve-selection="true"
            type="selection"
            width="55"
          />
          <slot name="table"></slot>
        </el-table>
        <Pages
          v-if="props.type === 'table' || props.type === 'checkBox'"
          style="margin-top: 10px"
          v-model:page="page"
          :small="true"
          :getTableData="getTableData"
        ></Pages>
      </div>
      <div v-if="props.showRight" class="right">
        <div class="use_titile">已选择</div>
        <SelectList
          :filterList="filterList"
          :keyId="props.selectKey"
          v-model:selectList="selectList"
        >
          <template #selectName="{ item }">
            <slot name="selectName" :item="item"></slot>
          </template>
        </SelectList>
        
      </div>
    </div>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ElTable } from 'element-plus'
import SelectList from "./selectList.vue";
const props = defineProps({
  dialogVisible: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  formItems: {
    type: Object,
  },
  searchParams: {
    type: Object,
  },
  getData: {
    type: Function,
  },
  resetFormCallBack: {
    type: Function,
  },
  type: {
    type: String,
  },
  selecedList: {
    type: Array,
  },
  selectTitle: {
    type: String,
  },
  selectKey: {
    type: String,
  },
  custom_checkBox: {
    type: Boolean,
    default: false,
  },
  cateListChildrenKey: {
    type: String,
  },
  showRight: {
    type: Boolean,
    default: true,
  },
})
const activeNames = ref([])
watch(
  () => activeNames.value,
  (val) => {
    console.log(val)
  }
)
const queryData = ref({ ...props.searchParams })
const emit = defineEmits([
  'update:searchParams',
  'update:selecedList',
  'update:dialogVisible',
])
watch(
  () => queryData,
  (val) => {
    emit('update:searchParams', val.value)
  },
  { deep: true }
)
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const isChecked = (item) => {
  return item[props.cateListChildrenKey].findIndex((e) => !e.checked) === -1
}
const list = ref([])
const checkAll = ref(false)
// 控制全选状态 checkBox
const indeterminate = computed(() => {
  const checkedCount = list.value.filter((e) => e.checked).length
  checkAll.value = checkedCount !== 0 && checkedCount === list.value.length
  return checkedCount > 0 && checkedCount < list.value.length
})
const handleSelectionChange = (rows, row) => {
  if (rows.findIndex((e) => e[props.selectKey] === row[props.selectKey]) > -1) {
    selectList.value.push(row)
  } else {
    selectList.value = selectList.value.filter(
      (v) => v[props.selectKey] != row[props.selectKey]
    )
  }
}
const selectAll = (rows) => {
  const key = props.selectKey
  if (props.type === 'cate-list') {
    selectList.value = []
    if (rows) {
      list.value.forEach((e) => {
        e.checked = true
        if (e[props.cateListChildrenKey]) {
          e[props.cateListChildrenKey].forEach((n) => {
            selectList.value.push(n)
            n.checked = true
          })
        }
      })
    } else {
      list.value.forEach((e) => {
        e.checked = false
        if (e[props.cateListChildrenKey]) {
          e[props.cateListChildrenKey].forEach((n) => {
            n.checked = false
          })
        }
      })
    }
    console.log(list.value)
  } else if (rows === true || rows.length > 0) {
    const selectSet = selectList.value.map((item) => item[key])
    list.value.forEach((item) => {
      if (rows === true) item.checked = true
      if (!selectSet.includes(item[key])) selectList.value.push(item)
    })
  } else {
    list.value.forEach((item) => {
      if (rows === false) item.checked = false
      for (let index = 0; index < selectList.value.length; index++) {
        if (selectList.value[index][key] == item[key]) {
          selectList.value.splice(index, 1)
        }
      }
    })
  }
}
watch(
  () => [...props.selecedList],
  () => {
    selectList.value = [...props.selecedList]
  }
)
const selectList = ref([...props.selecedList])
const loading = ref(false)
const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
})

const getTableData = async () => {
  let data = {
    data: {
      ...queryData.value,
    },
    pageSize: page.pageSize,
    pageNumber: page.currentPage,
  }
  list.value = []
  loading.value = true
  try {
    let res = await props.getData(data)
    list.value = res.data.content || res.data
    page.total = res.data.total * 1
    filterList()
    loading.value = false
  } catch (error) {
    loading.value = false
    list.value = []
  }
}
const filterList = () => {
  const key = props.selectKey
  if (props.type === 'table') {
    nextTick(() => {
      multipleTableRef.value!.clearSelection()
    })
    list.value.forEach((row) => {
      if (selectList.value.findIndex((v) => row[key] == v[key]) > -1) {
        nextTick(() => {
          multipleTableRef.value!.toggleRowSelection(row, true)
        })
      }
    })
  } else if (props.type === 'checkBox') {
    list.value.forEach((e) => {
      e.checked = false
      if (selectList.value.findIndex((v) => e[key] == v[key]) > -1) {
        e.checked = true
      }
    })
  } else if (props.type === 'cate-list') {
    list.value.forEach((e) => {
      if (e[props.cateListChildrenKey]) {
        e[props.cateListChildrenKey].forEach((n) => {
          n.checked = false
          if (selectList.value.findIndex((v) => n[key] == v[key]) > -1) {
            n.checked = true
          }
        })
        e.checked =
          e[props.cateListChildrenKey].findIndex((m) => !m.checked) === -1
      }
    })
  }
}
const defaultSearchParams = { ...props.searchParams }
const handleSearch = (data) => {
  if (data === null) {
    emit('update:searchParams', { ...defaultSearchParams })
    props.resetFormCallBack && props.resetFormCallBack()
  }
  page.currentPage = 1
  getTableData()
}
// cate-list
const handleSelect = (node, selectList, key, childrenKey, isChecked) => {
  node.checked = isChecked
  if (node[childrenKey]) {
    node[childrenKey].forEach((child) => {
      handleSelect(child, selectList, key, childrenKey, isChecked)
    })
  } else {
    const index = selectList.findIndex((item) => item[key] === node[key])
    if (isChecked && index === -1) {
      selectList.push(node)
    } else if (!isChecked && index > -1) {
      selectList.splice(index, 1)
    }
  }
}
// checkBox
const onChange = (e) => {
  const key = props.selectKey
  if (props.type === 'cate-list') {
    handleSelect(e, selectList.value, key, props.cateListChildrenKey, e.checked)
    list.value.forEach((item) => {
      item.checked = isChecked(item)
    })
  } else if (e.checked) {
    selectList.value.push(e)
  } else {
    selectList.value = selectList.value.filter((v) => v[key] != e[key])
  }
}

const getRowKeys = (row) => {
  return row[props.selectKey]
}
const handleOk = () => {
  emit('update:selecedList', selectList.value)
  handleCancel()
}
const handleCancel = () => {
  emit('update:dialogVisible', false)
}
onMounted(() => {
  getTableData()
})
defineExpose({ selectList, onChange, list })
</script>
<style lang="scss" scoped>
.dialog__body {
  display: flex;

  .left {
    flex: 1;
    width: 0;
  }

  .right {
    width: 30%;
    border-left: 1px solid #ccc;
    padding-left: 10px;
  }
}
:deep(.el-form--inline .el-form-item) {
  margin-right: 8px;
}

:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}
.el-collapse {
  border-top: none;
  border-bottom: none;
}
:deep(.el-collapse-item__header) {
  border-bottom: none;
  height: 30px;
  line-height: 30px;
  display: block;
  padding-left: 20px;
  position: relative;
}
:deep(.el-collapse-item__arrow) {
  position: absolute;
  left: 4px;
  top: 9px;
}
</style>
